package com.siyoumi.app.test.modules.sys.api;

import com.siyoumi.app.sys.service.wxapi.ApiConfig;
import com.siyoumi.app.sys.service.wxapi.WxApiPay;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

//@SpringBootTest
public class testWxApiPay {
    @Test
    @DisplayName("下单")
    void test100() {
        ApiConfig apiConfig = new ApiConfig();
        apiConfig.setPayAppId("wx55213f78d79c5ce1");
        apiConfig.setMchId("1623931778");
        apiConfig.setMchKey("fubakefubakefubake99999999999999");

        WxApiPay pay = WxApiPay.getIns();
        pay.setConfig(apiConfig);

        String orderId = "123123123123";
        XReturn r = pay.order(orderId, 1, "test", "oWW_Z5HqzwUp2W1cNWgYWzQ9Kw2A");
        //String r = pay.certificates();
        //XReturn r = pay.orderInfo("xxx");


        XLog.debug(this.getClass(), r);
        Assert.isTrue(r.ok(), r.getErrMsg());
    }

    @Test
    @SneakyThrows
    void test300() {
        String signatureStr = "test";

        String pkFilePath = "C:\\zzz_wx\\_cert\\1609208339_key.pem";
        PrivateKey pk = getPrivateKey(pkFilePath);
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(pk);
        sign.update(signatureStr.getBytes(StandardCharsets.UTF_8));

        String sign1 = new String(sign.sign());
        XLog.debug(this.getClass(), sign1);
    }


    /**
     * 获取私钥。
     *
     * @param filename 私钥文件路径  (required)
     * @return 私钥对象
     */
    @SneakyThrows
    public static PrivateKey getPrivateKey(String filename) {

        String content = Files.readString(Paths.get(filename));
        String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s+", "");

        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(
                new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
    }
}
